import React, { Component } from 'react'
import { reqgetcate, reqgetgoods } from '../../http/api';
import { SideBar, SearchBar, Card } from 'antd-mobile';
import Header from '../../components/Header/Header';
import "./Cate.less"
import { MyContext } from '../../App';

export default class Cate extends Component {
  constructor() {
    super();
    this.state = {
      //获取商品分类
      cate: [],
      //获取分类商品
      goods: [],
      n:1

    }
  }
  changeCate = (e) => {
    //获取分类商品
    reqgetgoods({ fid: e }).then(res => {
      if (res.data.code == 200) {
        this.setState({
          goods: res.data.list,
          n:e
        })
        console.log(res);
      }
    })
  }
  UNSAFE_componentWillMount(){
    this.changeCate(1)
  }
  render() {
    let { goods, cate,n } = this.state
    return (
      <div>
        <Header text="商品分类"></Header>
        {/* 搜索框 */}
        <header>
          <div>
            <SearchBar placeholder='请输入内容' />
            <button>搜索</button>
          </div>
        </header>
        <content>
          <SideBar activeKey={n+""} onChange={(e) => this.changeCate(Number(e))}>
            {cate.map(item => (
              <SideBar.Item
                key={item.id}
                title={item.catename}
              />
            ))}
          </SideBar>
          <div>
            {goods.map((item) => {
              return (
                <MyContext.Consumer key={item.id}>
                  {({ $pre }) => {
                    return (
                      <Card title={item.goodsname} onClick={() => { }}>
                        <img src={$pre+item.img} alt="" width={60} />
                        <div>
                          <p>价格:{item.price}</p>
                          <p>原价：{item.market_price}</p>
                        </div>
                        <button onClick={()=>this.props.history.push("/detail/id="+item.id)}>加入购物车</button>
                      </Card>
                    )
                  }}
                </MyContext.Consumer>
              )
            })}
          </div>
        </content>
        {/* <div>goods:{JSON.stringify(goods)}</div> */}
      </div>
    )
  }
  //渲染完成
  componentDidMount() {
    //获取商品分类
    reqgetcate().then(res => {
      if (res.data.code == 200) {
        this.setState({
          cate: res.data.list
        })
      }
    })
    //获取分类商品
    // changeCate=(e)=>{
    //  console.log(e);
    // }

  }
}
